var ws;
$(function(){
    link();
})

function link () {
    ws = new WebSocket("ws://106.12.201.205:9501");//连接服务器
    ws.onopen = function(event){
        //console.log(event);
        alert('连接了');
        sendIdentity();
    };
    ws.onmessage = function (event) {
        //console.log(event.data);return;
        var data = JSON.parse(event.data);
        console.log(data);

        localStorage.setItem('ws_vip_id', data['userFd']);
        localStorage.setItem('ws_vip_to_id', data['toUserFd']);
        localStorage.setItem('ws_vip_chat_id', data['chat_id']);
        var myInfo = '我是' + data['userFd'] + '号（会员）';
        if (data['toUserFd']) {
            userInfo = '我在和' + data['toUserFd'] + '号（客服）聊天';
        } else {
            userInfo = '当前没有客服在线';
        }
        $("#myInfo").text(myInfo);
        $("#userInfo").text(userInfo);
        if (data['type'] == 3) {

            return;
        }

        var msg = "<div class=\"pnl-list\" id=\"msgs\">\n" +
            "                                <div class=\"msg robot\" id=\"welcome\">\n" +
            "                                    <div class=\"msg-left\" id=\"welcomeLeft\">\n" +
            "                                        <div class=\"msg-host photo\" id=\"welcomeIcon\" style=\"background-image: url(&quot;https://www.v5kf.com/files/icons/201610/14761555537.png&quot;);\"></div>\n" +
            "                                        <div class=\"msg-ball\" id=\"welcomeBall\"><span>"+replace_em(data['msg'])+"</span></div>\n" +
            "                                    </div>\n" +
            "                                </div>";
        $("#show").append(msg);
        // var scrollTop = $("#msgArea")[0].scrollHeight;
        // $("#msgArea").scrollTop(scrollTop);
    }
    ws.onclose = function(event){
        alert("已经与服务器断开连接\r\n当前连接状态："+this.readyState);
    };

    ws.onerror = function(event){
        alert("请登录后重新打开对话框");
    };
}

function sendMsg(){
    var msg = $("#text").val();
    if (!msg) {
        alert('发送的数据不能为空');
        return;
    }
    var data = {type:2,userFd:localStorage.getItem('ws_vip_id'),toUserFd:localStorage.getItem('ws_vip_to_id'),msg:msg,chat_id:localStorage.getItem('ws_vip_chat_id')};
    $("#text").val('');
    var msg = "<div class=\"msg guest\" id=\"1543389702033-0\">\n" +
        "                                <div class=\"msg-right\">\n" +
        "                                    <div class=\"msg-host\"><i class=\"ic kh\"></i></div>\n" +
        "                                    <div class=\"msg-ball\" title=\"今天 15:38:29\">"+replace_em(msg)+"</div>\n" +
        "                                </div>\n" +
        "                            </div>";
    $("#show").append(msg);
    ws.send(JSON.stringify(data));
}

function sendIdentity() {
    var data = {type:3,userFd:localStorage.getItem('ws_vip_id'),identity_type:2,toUserFd:localStorage.getItem('ws_vip_to_id')};
    ws.send(JSON.stringify(data));
}

function replace_em(str) {
    str = str.replace(/\</g, '&lt;');
    str = str.replace(/\>/g, '&gt;');
    str = str.replace(/\n/g, '<br/>');
    str = str.replace(/\[:([\s\S]+?)\]/g, '<img src="gif/$1.gif" border="0" />');
    str = str.replace(/!\[([\s\S]+?)\]/g, '<img src="$1" border="0" />');
    return str;
}

function uploadFile(obj, type) {

    $.ajaxFileUpload({
        url : "http://swoole.upload.guardevil.cn/upload.php",
        secureuri : false,// 一般设置为false
        fileElementId : "fileUpload"+type,// 文件上传表单的id <input type="file" id="fileUpload" name="file" />
        dataType : 'json',// 返回值类型 一般设置为json
        data: {'type': type},

        success : function(data) // 服务器成功响应处理函数
        {
            $("#fileUpload1").val("");
            console.log('success:' + data);
        },
        error : function(data)// 服务器响应失败处理函数
        {
            console.log('error:' + data);
            console.log("服务器异常");
        }
    });
    return false;
}